package com.chinamobile.scm;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadFile
 */
@WebServlet("/UploadFile")
public final class UploadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String DESTINATION_DIR_PATH ="/files";
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadFile() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		java.io.File destinationDir = new java.io.File(realPath);
		if(!destinationDir.isDirectory()) {
			throw new ServletException(destinationDir+" is not a directory");
		}

		//java.io.File f=new java.io.File("E:\\src");
		// Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(!isMultipart) return;
		List<FileItem>  items = null;
		response.setContentType("text/html");
		
		//response.getOutputStream().println(b)
		// Parse the request
		try {
			items= upload.parseRequest(request);
			
			String filename=null;
			for(FileItem item : items){		
				if(item.isFormField() && item.getFieldName().equals("path")){
					filename=item.getString();
					break;
				}
			}
			
			if(filename==null || filename.isEmpty() || filename.contains("\\") || filename.contains("/"))
				return ;
			for(FileItem item : items){				
				if(item.isFormField()) continue;
				java.io.File file = new java.io.File(destinationDir,filename);
				item.write(file);							
				String url=response.encodeURL(request.getRequestURI().replace(request.getServletPath(), "/files/"+filename));
				response.getOutputStream().println(String.format("<a href=\"%s\">%s</a>",url,url));
			}				
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
